/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Company;
import cn.net.ecode.modules.sys.service.CompanyService;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 公司管理Controller
 * @author 冯伟、ThinkGem\jiaoanjian
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/company")
public class CompanyController extends BaseController {

	@Autowired
	private CompanyService companyService;

	@ModelAttribute
	public Company get(String companyCode, boolean isNewRecord) {
		return companyService.get(companyCode, isNewRecord);
	}

	@RequiresPermissions("sys:company:view")
	@RequestMapping(value = {"list", ""})
	public String list(Company company, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/sys/companyList";
	}

	@RequiresPermissions("sys:company:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Company> listData(Company company) {
		if (StringUtils.isBlank(company.getParentCode())) {
			company.setParentCode(Company.ROOT_CODE);
		}
		List<Company> list = null;
		if (StringUtils.isNotBlank(company.getCompanyCode())) {
			list = Lists.newArrayList(get(company.getCompanyCode(), false));
		} else {
			list = companyService.findList(company);
		}
		return list;
	}

	@RequiresPermissions("sys:company:view")
	@RequestMapping(value = "form")
	public String form(Company company, Model model, HttpServletRequest request) {
		if (company.getParent() != null && StringUtils.isNotBlank(company.getParent().getCompanyCode())) {
			company.setParent(companyService.get(company.getParent().getCompanyCode()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(company.getCompanyCode())) {
				Company companyChild = new Company();
				companyChild.setParent(new Company(company.getParent().getCompanyCode()));
				List<Company> list = companyService.findList(company);
				if (list.size() > 0) {
					company.setSorts(list.get(list.size() - 1).getSorts());
					if (company.getSorts() != null) {
						company.setSorts(company.getSorts() + 30);
					}
				}
			} else {
				//如果id不为空，获取关联的组织结构
				Company company2 = new Company();
				company2.setId(company.getCompanyCode());
				company2 = companyService.getOffices(company2);
				company.setOffice(company2.getOffice());
			}
		}
		if (company.getSorts() == null) {
			company.setSorts(30);
		}
		model.addAttribute("company", company);
		return "modules/sys/companyForm";
	}

	@RequiresPermissions("sys:company:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Company company) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		StringBuilder builder = new StringBuilder();
		if (!beanValidator(builder, company)) {
			return renderResult(Global.FALSE, builder.toString());
		}
		companyService.save(company);
		return renderResult(Global.TRUE, "保存公司'" + company.getCompanyName() + "'成功！");
	}

//	@RequiresPermissions("sys:company:edit")
//	@RequestMapping(value = "delete")
//	public String delete(Company company) {
//		if(Global.isDemoMode()){
//			return renderResult(Global.FALSE, "演示模式，不允许操作！");
//		}
//		companyService.delete(company);
//		return renderResult(Global.TRUE, "删除公司成功！");
//	}

	@RequiresPermissions("sys:company:disable")
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(Company company, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		List<Company> companyList = companyService.getEnabledList(company);
		if (companyList != null && companyList.size() > 0) {
			return renderResult(Global.FALSE, "公司" + company.getCompanyName() + "包含未停用的公司，请先停用子节点！");
		}
		companyService.disable(company);
		return renderResult(Global.TRUE, "停用公司" + company.getCompanyName() + "成功");
	}

	@RequiresPermissions("sys:company:disable")
	@ResponseBody
	@RequestMapping(value = "disableByGroup")
	public String disableByGroup(Company company) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		companyService.disableByGroup(company);
		return renderResult(Global.TRUE, "停用公司" + company.getCompanyName() + "及子公司成功");
	}

	@RequiresPermissions("sys:company:enable")
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(Company company) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		companyService.enable(company);
		return renderResult(Global.TRUE, "启用公司" + company.getCompanyName() + "成功");
	}

	@RequiresPermissions("sys:company:enable")
	@ResponseBody
	@RequestMapping(value = "enableByGroup")
	public String enableByGroup(Company company) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		companyService.enableByGroup(company);
		return renderResult(Global.TRUE, "启用公司" + company.getCompanyName() + "及子公司成功");
	}

	/**
	 * 获取公司JSON数据。
	 * @param extCode 排除的ID
	 * @param isAll 是否显示所有机构（true：不进行权限过滤）
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @param isShowFullName 是否显示全公司名称
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String extCode, Boolean isAll, String isShowCode, String isShowFullName) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Company> list = companyService.findList(isAll);
		for (int i = 0; i < list.size(); i++) {
			Company e = list.get(i);
			if (StringUtils.isBlank(extCode)
					|| (extCode != null && !extCode.equals(e.getCompanyCode()) && e.getParentCodes().indexOf("," + extCode + ",") == -1)
					&& (e.getStatus().equals(Company.STATUS_NORMAL))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getCompanyCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				String name = e.getCompanyNameSimple();
				if ("true".equals(isShowFullName) || "1".equals(isShowFullName)){
					name = e.getCompanyName();
				}
				if ("true".equals(isShowCode) || "1".equals(isShowCode)){
					map.put("name", "(" + e.getViewCode() + ")" + name);
				}else if ("2".equals(isShowCode)){
					map.put("name", name + "(" + e.getViewCode() + ")");
				}else{
					map.put("name", name);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

	@RequiresPermissions("sys:company:edit")
	@ResponseBody
	@RequestMapping(value = "dataFix")
	public String dataFix() {
		companyService.updateFixParentCodes();
		return renderResult(Global.TRUE, "数据修复成功");
	}

}